import type { Request, ResponseToolkit } from "@hapi/hapi";
import Bcrypt from "bcryptjs";
import Hapi from "@hapi/hapi";
import Joi from "joi";
import Boom from "@hapi/boom";
import { User } from "../../model/index";
import jwt from "jsonwebtoken";
import { userSchema } from "../schema/index";
interface user {
  account: string;
  password: string;
  _id: string;
}
let route: Hapi.ServerRoute<Hapi.ReqRefDefaults> = {
  path: "/login",
  method: "get",
  handler: async (r: Request, h: ResponseToolkit) => {
    try {
      console.log(11);
      const { account, password } = r.query;
      const user: user | null = await User.findOne({ account });
      if (user) {
        const isValid = Bcrypt.compareSync(password, user.password);
        if (!isValid) {
          throw Boom.unauthorized("密码错误");
        }
        console.log(user._id);

        const token = jwt.sign({ userId: user._id }, "123456", {
          expiresIn: "1d",
        });

        return {
          data: { token, account: user.account },
          code: 200,
          message: "",
        };
      } else {
        return h
          .response({
            error: { message: "用户不存在", code: 404 },
          })
          .code(400);
      }
    } catch (error) {
      return error;
    }
  },
  options: {
    auth: false,
    tags: ["api"],
    validate: {
      query: userSchema,
    },
  },
};
export default route;
